package com.drinks.yiniang.ui.activity.user;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.entity.common.UploadImageJson;
import com.drinks.yiniang.entity.user.UserInfoJson;
import com.drinks.yiniang.io.api.CommonApiIO;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.io.http.ProgressRequestBody;
import com.drinks.yiniang.ui.activity.user.invoice.InvoiceManageActivity;
import com.drinks.yiniang.ui.activity.user.setting.ChooseSexActivity;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.drinks.yiniang.ui.activity.common.PublicInputActivity;
import com.hansen.library.ui.widget.image.CircleImageView;
import com.hansen.library.ui.widget.layout.TextTextArrowLayout;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.pickerimage.PickImageHelper;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.io.File;

import static com.hansen.library.pickerimage.constant.Extras.EXTRA_FILE_PATH;

/**
 * 个人资料页面
 *
 * @author han
 * @date 2019/09/03
 */
public class UserDataActivity extends BaseTranBarActivity implements OnNavgationBarClickListener {

    private final int REQ_UPLOAD_AVATAR_CODE = 0x01;
    private final int REQ_MODIFY_NICKNAME_CODE = 0x02;
    private final int REQ_MODIFY_SEX_CODE = 0x03;
    private final int REQ_MODIFY_SIGNATURE_CODE = 0x04;

    private final String KEY_AVATAR = "avatar";

    //nav
    private NavigationBarLayout nav_bar_user_data;
    //头像
    private CircleImageView iv_user_data_avatar;
    private ImageView iv_user_data_avatar_arrow;
    //昵称
    private TextTextArrowLayout ttal_user_data_nickname;
    //性别
    private TextTextArrowLayout ttal_user_data_sex;
    //个性签名
    private TextTextArrowLayout ttal_user_data_signature;
    //发票管理
    private TextView tv_user_data_invoice;

    private PickImageHelper.PickImageOption pickImgOption;

    private boolean isNeedSetResult;

    @Override
    protected void initView() {
        nav_bar_user_data = findViewById(R.id.nav_bar_user_data);

        iv_user_data_avatar = findViewById(R.id.iv_user_data_avatar);
        iv_user_data_avatar_arrow = findViewById(R.id.iv_user_data_avatar_arrow);

        ttal_user_data_nickname = findViewById(R.id.ttal_user_data_nickname);
        ttal_user_data_sex = findViewById(R.id.ttal_user_data_sex);
        ttal_user_data_signature = findViewById(R.id.ttal_user_data_signature);

        tv_user_data_invoice = findViewById(R.id.tv_user_data_invoice);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        getUserInfo();
    }

    @Override
    protected void initListener() {
        nav_bar_user_data.setOnNavgationBarClickListener(this);
        iv_user_data_avatar.setOnClickListener(this);
        iv_user_data_avatar_arrow.setOnClickListener(this);
        ttal_user_data_nickname.setOnClickListener(this);
        ttal_user_data_sex.setOnClickListener(this);
        ttal_user_data_signature.setOnClickListener(this);
        tv_user_data_invoice.setOnClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        Intent mIntent;

        switch (v.getId()) {
            case R.id.iv_user_data_avatar://更换头像
            case R.id.iv_user_data_avatar_arrow:
                initPickerImage();
                break;
            case R.id.ttal_user_data_nickname://修改昵称
                mIntent = new Intent(mContext, PublicInputActivity.class);
                mIntent.putExtra(Constants.KeyTitle, getString(R.string.text_user_nickname));
                mIntent.putExtra(Constants.KeyTextContents, ttal_user_data_nickname.getArrowText());
                mIntent.putExtra(Constants.KeyHint, getString(R.string.text_hint_input_nickname));
                mIntent.putExtra(Constants.KeyType, PublicInputActivity.TYPE_API_USERNAME);
                startActivityForResult(mIntent, REQ_MODIFY_NICKNAME_CODE);
                break;
            case R.id.ttal_user_data_sex://修改性别
                mIntent = new Intent(mContext, ChooseSexActivity.class);
                startActivityForResult(mIntent, REQ_MODIFY_SEX_CODE);
                break;
            case R.id.ttal_user_data_signature://修改签名
                mIntent = new Intent(mContext, PublicInputActivity.class);
                mIntent.putExtra(Constants.KeyTitle, getString(R.string.text_signature));
                mIntent.putExtra(Constants.KeyTextContents, ttal_user_data_signature.getArrowText());
                mIntent.putExtra(Constants.KeyHint, getString(R.string.text_hint_input_signature));
                mIntent.putExtra(Constants.KeyShowMax, true);
                mIntent.putExtra(Constants.KeyShow, true);
                mIntent.putExtra(Constants.KeyMaxLength, 30);
                mIntent.putExtra(Constants.KeyType, PublicInputActivity.TYPE_API_SIGNATURE);
                startActivityForResult(mIntent, REQ_MODIFY_SIGNATURE_CODE);
                break;
            case R.id.tv_user_data_invoice://发票管理
                mIntent = new Intent(mContext, InvoiceManageActivity.class);
                startActivity(mIntent);
                break;
            default:
                break;
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_user_data;
    }

    @Override
    public void onBackClick(View v) {
        doFinish();
    }

    @Override
    public void onEditClick(View v) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            doFinish();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    private void doFinish() {
        if(isNeedSetResult) {
            setResult(Constants.RESULT_CODE_NORMAL);
        }
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constants.RESULT_CODE_NORMAL && data != null) {
            switch (requestCode) {
                case REQ_MODIFY_NICKNAME_CODE:
                    isNeedSetResult = true;
                    setNickname(data.getStringExtra(Constants.KeyTextContents));
                    break;
                case REQ_MODIFY_SEX_CODE:
                    isNeedSetResult = true;
                    setSexData(data.getStringExtra(Constants.KeyTextContents));
                    break;
                case REQ_MODIFY_SIGNATURE_CODE:
                    isNeedSetResult = true;
                    setSignature(data.getStringExtra(Constants.KeyTextContents));
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQ_UPLOAD_AVATAR_CODE://选择图片回调
                    uploadFile(data.getStringExtra(EXTRA_FILE_PATH));
                    break;
                default:
                    break;
            }
        }
    }

    //选择图片
    private void initPickerImage() {
        if (pickImgOption == null) {
            pickImgOption = new PickImageHelper.PickImageOption();
            pickImgOption.crop = true;
            pickImgOption.multiSelect = false;
            pickImgOption.cropOutputImageWidth = 360;
            pickImgOption.cropOutputImageHeight = 360;
        }

        PickImageHelper.pickImage(mContext, REQ_UPLOAD_AVATAR_CODE, pickImgOption);
    }

    //上传图片
    private void uploadFile(String path) {
        if (StringUtils.isEmpty(path)) {
            return;
        }

        File file = new File(path);

        if (file == null) {
            return;
        }

        showLoadingDialog(R.string.text_uploading_dot);

        CommonApiIO.getInstance().uploadImage(file, new ProgressRequestBody.ProgressListener() {
            @Override
            public void onProgress(long totalSize, long currSize, boolean done, int id) {

            }
        }, new APIRequestCallback<UploadImageJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(UploadImageJson res) {
                if (StringUtils.isEmpty(res.getData().getId())) {
                    dismissDialog();
                    return;
                }

                GlideUtils.loadAvatar(mContext, iv_user_data_avatar, res.getData().getOriginal());

                doModifyUserInfo(res.getData().getId());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                dismissDialog();
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void doModifyUserInfo(String value) {
        showLoadingDialog(R.string.text_waiting_loading);

        UserApiIO.getInstance().modifyUserInfo(KEY_AVATAR, value, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                isNeedSetResult = true;
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //获取个人信息
    private void getUserInfo() {
        showLoadingDialog();

        UserApiIO.getInstance().getUserInfo(new APIRequestCallback<UserInfoJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(UserInfoJson res) {
                GlideUtils.loadAvatar(mContext, iv_user_data_avatar, res.getData().getAvatar());
                setNickname(res.getData().getUsername());
                setSexData(res.getData().getSex());
                setSignature(res.getData().getSignature());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void setNickname(String name) {
        ttal_user_data_nickname.setArrowText(name);
    }

    private void setSexData(String sex) {
        ttal_user_data_sex.setArrowText(CommonUtils.getSexByCode(sex));
    }

    private void setSignature(String signature) {
        ttal_user_data_signature.setArrowText(signature);
    }
}
